/**
 * 
 */
package org.yelongframework.servlet.http.reusebody;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.io.IOUtils;
import org.yelongframework.servlet.ByteArrayServletInputStream;

/**
 * 可以重复请求消息体的包装器
 * 
 * @since 1.0.0
 */
public class ReuseHttpServletRequestWrapper extends HttpServletRequestWrapper {

	/** 请求消息体 */
	private final byte[] body;

	// ==================================================constructor==================================================

	public ReuseHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
		super(request);
		body = readBodyByteArray(request);
	}

	// ==================================================override==================================================

	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(getInputStream()));
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		return new ByteArrayServletInputStream(body);
	}

	// ==================================================读取==================================================

	protected byte[] readBodyByteArray(HttpServletRequest request) throws IOException {
		return IOUtils.toByteArray(request.getInputStream());
	}

	// ==================================================工具==================================================

	/**
	 * @return 获取请求消息体
	 */
	public byte[] getBodyByteArray() {
		return body;
	}

}
